package com.kosmos.dubhe.wxcp.provider;

import com.kosmos.dubhe.wxcp.config.WxCpConfiguration;

import com.kosmos.dubhe.wxcp.setting.WxcpDepartmentScannerSetting;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;

import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.NoSuchElementException;


/**
 * @author wukai
 */
@Component
@Data
@Slf4j
public class WxCpDepartmentProvider {
    List<WxCpDepart> departmentList;
    private final WxcpDepartmentScannerSetting setting;

    @PostConstruct
    public void init() {
        syncDepartment();
    }

    public Long getDepartmentId(String departmentName) {
        try {
            val department = departmentList.stream().filter(u -> departmentName.equals(u.getName())).findFirst().orElseThrow(
                    () -> new RuntimeException(String.format(
                            "WxCpDepartmentProvider getDepartmentByName to query departmentName:[%s] , department not exist , ", departmentName)));
            return department.getId();
        } catch (NoSuchElementException e) {
            String message = String.format("WxCpDepartmentProvider getDepartmentCode to query departmentName:[%s] , department not exist , ", departmentName);
            log.error(message);
            throw new NoSuchElementException(message);
        }
    }

    public void syncDepartment() {
        try {
            departmentList = WxCpConfiguration.getCpService(setting.getAgentId())
                    .getDepartmentService()
                    .list(setting.getRootDepartmentId());
            log.debug("-------- syncDepartment --------");
            departmentList.forEach(t -> log.debug("department: [{}], name:[{}]", t.getId(), t.getName()));
        } catch (WxErrorException e) {
            log.error("DepartmentProvider syncDepartment occur exception ", e);
        }
    }

}
